<template>
  <div class="patrol-plan-add">
    <div class="container">
      <div class="form-header">
        <div class="form-title">
          <i class="el-icon-edit-outline"></i> 添加巡更计划
          <el-button 
            icon="el-icon-back" 
            class="back-button" 
            type="text" 
            size="medium" 
            @click="goBack">返回</el-button>
        </div>
        <div class="form-subtitle">填写巡更计划信息来创建新的巡更任务</div>
      </div>

      <el-card class="form-card">
        <div v-loading="loading" class="form-content">
          <div class="form-section">
            <div class="section-title">基本信息</div>
            
            <div class="form-item">
              <div class="form-label"><span class="required">*</span>选择小区：</div>
              <div class="form-control">
                <el-select 
                  v-model="formData.communityId" 
                  placeholder="请选择小区" 
                  class="form-input"
                  :loading="loadingCommunities">
                  <el-option 
                    v-for="item in communityOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="form-item">
              <div class="form-label"><span class="required">*</span>巡更计划名称：</div>
              <div class="form-control">
                <el-input 
                  v-model="formData.planName" 
                  placeholder="请输入巡更计划名称" 
                  class="form-input">
                </el-input>
                <div class="form-tip">输入名称说明，最多不超过30个字符</div>
              </div>
            </div>
          </div>

          <div class="form-section">
            <div class="section-title">时间设置</div>

            <div class="form-item">
              <div class="form-label"><span class="required">*</span>巡更频率：</div>
              <div class="form-control">
                <el-select 
                  v-model="formData.frequency" 
                  placeholder="请选择巡更频率" 
                  class="form-input">
                  <el-option label="每天" value="daily"></el-option>
                  <el-option label="每周" value="weekly"></el-option>
                  <el-option label="每月" value="monthly"></el-option>
                </el-select>
              </div>
            </div>
            
            <div class="form-item" v-if="formData.frequency === 'weekly'">
              <div class="form-label">选择星期：</div>
              <div class="form-control weekday-selector">
                <el-checkbox-group v-model="selectedWeekdays">
                  <el-checkbox label="1">周一</el-checkbox>
                  <el-checkbox label="2">周二</el-checkbox>
                  <el-checkbox label="3">周三</el-checkbox>
                  <el-checkbox label="4">周四</el-checkbox>
                  <el-checkbox label="5">周五</el-checkbox>
                  <el-checkbox label="6">周六</el-checkbox>
                  <el-checkbox label="0">周日</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
            
            <div class="form-item" v-if="formData.frequency === 'monthly'">
              <div class="form-label">选择日期：</div>
              <div class="form-control">
                <el-select 
                  v-model="formData.monthDays" 
                  multiple
                  collapse-tags
                  placeholder="请选择日期" 
                  class="form-input">
                  <el-option 
                    v-for="i in 31" 
                    :key="i" 
                    :label="i + '号'" 
                    :value="i">
                  </el-option>
                </el-select>
                <div class="form-tip">可多选，每月在选中的日期执行巡更</div>
              </div>
            </div>

            <div class="form-item">
              <div class="form-label"><span class="required">*</span>巡更时间：</div>
              <div class="form-control">
                <el-time-picker
                  v-model="formData.patrolTime"
                  format="HH:mm"
                  placeholder="选择具体时间"
                  class="form-input">
                </el-time-picker>
                <div v-if="showPatrolTimeError" class="error-message">请选择巡更时间</div>
              </div>
            </div>
          </div>

          <div class="form-section">
            <div class="section-title">巡更设置</div>
            
            <div class="form-item">
              <div class="form-label"><span class="required">*</span>所选路线：</div>
              <div class="form-control">
                <el-select 
                  v-model="formData.routeId" 
                  placeholder="请选择巡更路线" 
                  class="form-input"
                  :loading="loadingRoutes">
                  <el-option 
                    v-for="item in routeOptions" 
                    :key="item.routeId" 
                    :label="item.routeName" 
                    :value="item.routeId">
                  </el-option>
                </el-select>
              </div>
            </div>

            <div class="form-item">
              <div class="form-label">备注：</div>
              <div class="form-control">
                <el-input 
                  v-model="formData.remark" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入备注信息（选填）" 
                  class="form-input">
                </el-input>
              </div>
            </div>

            <div class="form-item">
              <div class="form-label">状态：</div>
              <div class="form-control">
                <el-radio-group v-model="formData.status">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
        </div>

        <div class="form-actions">
          <el-button type="primary" @click="submitForm" icon="el-icon-check" :loading="submitting">提交</el-button>
          <el-button @click="resetForm" icon="el-icon-refresh">重置</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        communityId: '',
        planName: '',
        frequency: 'weekly',
        weekdays: [false, false, false, false, false, false, false],
        monthDays: [],
        patrolTime: '',
        routeId: '',
        route: '',
        status: 1,
        remark: ''
      },
      selectedWeekdays: [],
      communityOptions: [],
      routeOptions: [],
      showPatrolTimeError: false,
      loading: false,
      loadingCommunities: false,
      loadingRoutes: false,
      submitting: false
    }
  },

  watch: {
    selectedWeekdays: {
      handler(newValues) {
        // 将选中的值转为weekdays数组
        this.formData.weekdays = [
          newValues.includes('0'),
          newValues.includes('1'),
          newValues.includes('2'),
          newValues.includes('3'),
          newValues.includes('4'),
          newValues.includes('5'),
          newValues.includes('6')
        ];
      },
      deep: true
    },
    
    'formData.communityId'(newVal) {
      // 当社区选择改变时，重新获取路线列表
      if (newVal) {
        this.fetchRoutes();
      } else {
        this.routeOptions = [];
        this.formData.routeId = '';
      }
    },
    
    'formData.routeId'(newVal) {
      // 当路线ID改变时，同步更新route字段（用于兼容）
      if (newVal) {
        const selectedRoute = this.routeOptions.find(route => route.routeId === newVal);
        if (selectedRoute) {
          this.formData.route = selectedRoute.routeName;
        }
      } else {
        this.formData.route = '';
      }
    },
    
    'formData.frequency'(newVal) {
      // 当频率改变时，重置相关字段
      if (newVal === 'daily') {
        // 选择每天，清空周几和月份
        this.selectedWeekdays = [];
        this.formData.weekdays = [false, false, false, false, false, false, false];
        this.formData.monthDays = [];
      } else if (newVal === 'weekly') {
        // 选择每周，清空月份
        this.formData.monthDays = [];
      } else if (newVal === 'monthly') {
        // 选择每月，清空周几
        this.selectedWeekdays = [];
        this.formData.weekdays = [false, false, false, false, false, false, false];
      }
    },
    
    'formData.monthDays'(newVal) {
      // 对月份日期进行排序
      if (newVal && newVal.length > 0) {
        // 使用slice()创建副本以避免无限循环
        const sortedDays = [...newVal].sort((a, b) => a - b);
        
        // 只有当排序后的数组与原数组不同时才更新
        if (JSON.stringify(sortedDays) !== JSON.stringify(newVal)) {
          this.formData.monthDays = sortedDays;
        }
      }
    }
  },

  methods: {
    goBack() {
      this.$router.go(-1);
    },

    submitForm() {
      // 重置错误标记
      this.showPatrolTimeError = false;
      
      // 表单验证
      if (!this.formData.communityId) {
        this.$message.error('请选择小区');
        return;
      }
      if (!this.formData.planName) {
        this.$message.error('请输入巡更计划名称');
        return;
      }
      if (!this.formData.patrolTime) {
        this.$message.error('请选择巡更具体时间');
        this.showPatrolTimeError = true;
        return;
      }
      
      // 根据频率验证相关字段
      if (this.formData.frequency === 'weekly' && !this.formData.weekdays.some(day => day)) {
        this.$message.error('请选择至少一个星期日');
        return;
      }
      
      if (this.formData.frequency === 'monthly' && this.formData.monthDays.length === 0) {
        this.$message.error('请选择至少一个日期');
        return;
      }
      
      if (!this.formData.routeId) {
        this.$message.error('请选择路线');
        return;
      }
      
      // 根据频率清理不需要的字段
      const submitData = { ...this.formData };
      if (submitData.frequency === 'daily') {
        delete submitData.weekdays;
        delete submitData.monthDays;
      } else if (submitData.frequency === 'weekly') {
        delete submitData.monthDays;
      } else if (submitData.frequency === 'monthly') {
        delete submitData.weekdays;
      }
      
      // 格式化时间为HH:mm:ss格式
      if (submitData.patrolTime) {
        const time = new Date(submitData.patrolTime);
        // 使用本地时间，不进行时区转换
        const hours = time.getHours().toString().padStart(2, '0');
        const minutes = time.getMinutes().toString().padStart(2, '0');
        const seconds = time.getSeconds().toString().padStart(2, '0');
        submitData.patrolTime = `${hours}:${minutes}:${seconds}`;
      }
      
      // 提交表单到后端API
      this.submitting = true;
      // 模拟API调用
      setTimeout(() => {
        // 这里应该替换为实际的API调用
        this.$axios.post('api/patrol-server/patrolPlan/addPatrolPlan', submitData)
          .then(response => {
            if (response.data && response.data.code === 200) {
              this.$message.success('巡更计划创建成功');
              this.$emit('submit', response.data.data);
              // 创建成功后返回上一页
              this.$router.go(-1);
            } else {
              this.$message.error(response.data.message || '创建失败，请稍后再试');
            }
          })
          .catch(error => {
            this.$message.error('创建失败，请稍后再试');
            console.error('提交表单出错:', error);
          });
        this.submitting = false;
      }, 500);
    },
    
    resetForm() {
      this.formData = {
        communityId: '',
        planName: '',
        frequency: 'weekly',
        weekdays: [false, false, false, false, false, false, false],
        monthDays: [],
        patrolTime: '',
        routeId: '',
        route: '',
        status: 1,
        remark: ''
      };
      this.selectedWeekdays = [];
      this.showPatrolTimeError = false;
    },
    
    fetchCommunities() {
      this.loadingCommunities = true;
      // 模拟API调用
      setTimeout(() => {
        // 这里应该替换为实际的API调用
        this.$axios.get('api/infrastructure-server/community/queryAll')
          .then(response => {
            if (response.data && response.data.code === 200) {
              this.communityOptions = response.data.data.map(item => {
                return { value: item.id, label: item.name };
              });
            }
          })
          .catch(error => {
            console.error('获取社区列表错误:', error);
          });
        this.loadingCommunities = false;
      }, 500);
    },
    
    fetchRoutes() {
      if (!this.formData.communityId) {
        return; // 如果没有选择社区，则不获取路线
      }
      
      this.loadingRoutes = true;
      this.routeOptions = []; // 清空已有选项
      this.formData.routeId = ''; // 重置路线选择
      
      // 模拟API调用
      setTimeout(() => {
        // 这里应该替换为实际的API调用，使用模板字符串时需要用反引号
        this.$axios.get(`api/patrol-server/patrolRoute/queryByCommunityId/${this.formData.communityId}`)
          .then(response => {
            if (response.data && response.data.code === 200) {
              // 修改映射字段，与模板中的字段保持一致
              this.routeOptions = response.data.data.map(item => {
                return { 
                  routeId: item.routeId || item.id, 
                  routeName: item.routeName || item.name 
                };
              });
              
              // 调试输出
              console.log('路线数据:', this.routeOptions);
            }
          })
          .catch(error => {
            console.error('获取路线列表错误:', error);
            // 如果接口出错，设置默认测试数据，使用正确的字段名
            this.routeOptions = [
              { routeId: 'route1', routeName: '路线一' },
              { routeId: 'route2', routeName: '路线二' }
            ];
          })
          .finally(() => {
            this.loadingRoutes = false;
          });
      }, 500);
    }
  },
  
  created() {
    this.loading = true;
    // 只需要获取社区列表，路线列表会在选择社区后获取
    this.fetchCommunities();
    // 使用setTimeout模拟接口加载完成
    setTimeout(() => {
      this.loading = false;
    }, 800);
  }
}
</script>

<style scoped>
.patrol-plan-add {
  background-color: #f5f7fa;
  padding: 20px;
  min-height: 100%;
  display: flex;
  justify-content: center;
}

.container {
  width: 100%;
  max-width: 800px;
}

.form-header {
  margin-bottom: 20px;
  text-align: center;
  position: relative;
}

.back-button {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
  padding: 0;
}

.form-title {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-title i {
  margin-right: 10px;
  font-size: 24px;
}

.form-subtitle {
  color: #909399;
  font-size: 14px;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 18px 0 rgba(0, 0, 0, 0.1);
}

.form-content {
  padding: 10px 30px;
  min-height: 400px;
}

.form-section {
  margin-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 22px;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.form-item {
  margin-bottom: 25px;
  display: flex;
  align-items: flex-start;
}

.form-label {
  width: 120px;
  text-align: right;
  padding-right: 12px;
  color: #606266;
  line-height: 40px;
  font-size: 14px;
}

.form-control {
  flex: 1;
}

.required {
  color: #f56c6c;
  margin-right: 4px;
}

.form-input {
  width: 100%;
  max-width: 320px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.weekday-selector {
  margin-top: 6px;
}

.weekday-selector .el-checkbox {
  margin-right: 15px;
  margin-left: 0;
  margin-bottom: 10px;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

.form-actions {
  margin-top: 30px;
  padding: 20px;
  text-align: center;
  border-top: 1px solid #ebeef5;
}

.form-actions .el-button {
  padding: 12px 25px;
  min-width: 120px;
  margin: 0 15px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .form-item {
    flex-direction: column;
  }
  
  .form-label {
    width: 100%;
    text-align: left;
    padding-right: 0;
    margin-bottom: 8px;
    line-height: normal;
  }
  
  .form-input {
    width: 100%;
  }
  
  .weekday-selector .el-checkbox {
    margin-right: 10px;
    margin-bottom: 8px;
  }
  
  .back-button {
    position: relative;
    transform: none;
    margin-bottom: 10px;
    display: block;
    left: auto;
    top: auto;
  }
  
  .form-title {
    flex-direction: column;
  }
}
</style>